package im.yisme.view.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import im.yisme.R;
import im.yisme.controler.service.CtrlServiceProvider;
import im.yisme.controler.service.LyricsCtrlService;
import im.yisme.model.Lyrics;
import im.yisme.model.service.LyricsRepositoryService;
import im.yisme.model.service.ModelServiceProvider;
import im.yisme.model.service.PlatformService;
import im.yisme.view.service.ViewService;
import im.yisme.view.service.ViewServiceProvider;
import im.yisme.view.tasks.YAsyncTask;
import im.yisme.view.ui.util.LyricsListAdapter;
import im.yisme.vo.LyricsVO;
import im.yisme.vo.MusicVO;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;

public class PlayLyricsListActivity extends Activity{
	private ListView lyricsListView;
	private LyricsRepositoryService model;
	private ViewService viewCtrl;
	private LyricsCtrlService ctrl;
	private PlatformService platformModel;
	
	
	private ArrayList<LyricsVO> lyricsVOList;
	private ArrayList<LyricsVO> downloadLyricsVOList;
	private Intent intent;
	
	private ImageButton backButton;
	
	private ArrayList<Map<String, Object>> data1;
    private ArrayList<Map<String, Object>> data2;
    private LyricsListAdapter adapter;
     
	protected void  onCreate(Bundle savedBundleInstance) {
		super.onCreate(savedBundleInstance);
		setContentView(R.layout.activity_playlyricslib);
		
		viewCtrl=ViewServiceProvider.getViewService();
		model = ModelServiceProvider.getLyricsRepositoryService();
		ctrl = CtrlServiceProvider.getLyricsCtrlService();
		platformModel = ModelServiceProvider.getPlatformService();
		
        lyricsListView = (ListView) findViewById(R.id.listView_lyrics);
        initButton();
        
        intent = getIntent();

        Iterator<LyricsVO> it = model.getLyricsForMusic((MusicVO)intent.getSerializableExtra("musicVO"));
        data1=new ArrayList<Map<String,Object>>();
        data2=new ArrayList<Map<String,Object>>();
        lyricsVOList = new ArrayList<LyricsVO>();
		downloadLyricsVOList = new ArrayList<LyricsVO>();
        
        while (it.hasNext()) {
			LyricsVO lyricsVO =  it.next();
			Map<String,Object> item = new HashMap<String,Object>();  
            item.put("lyricsName", lyricsVO.getName());  
            item.put("noteNum", lyricsVO.getNoteNum()+"");  
            item.put("duration", lyricsVO.getTotalTime());  
            data1.add(item);   
            lyricsVOList.add(lyricsVO);
		}
        
        
        
        Map<String,Object> item = new HashMap<String,Object>();
        item.put("lyricsName", "正在加载中...");  
        item.put("noteNum", "");  
        item.put("star", 0);  
        item.put("official", false);

        data2.add(item);
        
        
        adapter=new LyricsListAdapter(this, data1, data2);
        
      
        lyricsListView.setAdapter(adapter);
        
        lyricsListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(arg2 == 0 || arg2 == lyricsVOList.size()+1) return;
				
				LyricsVO lyricsVO = null;
				if(arg2 <= lyricsVOList.size()) lyricsVO = lyricsVOList.get(arg2-1);
				else {
					if(arg2-lyricsVOList.size()-1 <= downloadLyricsVOList.size())
						{
						DownloadTask task = new DownloadTask();
						task.execute(downloadLyricsVOList.get(arg2-lyricsVOList.size()-2).getRemoteId(),arg2-lyricsVOList.size()-2);
						}
				}
				
				if(lyricsVO == null) return;
				jumpToPlay(lyricsVO);
				overridePendingTransition(android.R.anim.fade_in, R.anim.musiclist_activity_zoomin);
			}
		});
        
        MusicVO musicVO = (MusicVO)intent.getSerializableExtra("musicVO");
        search(musicVO.getName());
	}

	private void search(String keyword){
		SearchTask task = new SearchTask();
		task.execute(keyword);
	}
	private void initButton() {
		// TODO Auto-generated method stub
		backButton = (ImageButton) findViewById(R.id.imageButton_back);
		backButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				jumpToUpper();
				overridePendingTransition(R.anim.musiclist_activity_zoomout	, android.R.anim.fade_out);
			}
		});
	}

	private void jumpToPlay(LyricsVO lyrics){
		Intent intent = new Intent(this,GameActivity.class);
		intent.putExtra("musicVO", this.intent.getSerializableExtra("musicVO"));
		intent.putExtra("lyricsVO", lyrics);
		viewCtrl.jumpTo(intent);
	}
	
	private void jumpToUpper(){
		Intent intent = new Intent(this,PlayMusicListActivity.class);
		viewCtrl.jumpTo(intent);
	}
	
	protected void onResume(){
		super.onResume();
		viewCtrl.updateTopActivity(this);
	}
	public void onBackPressed(){}
	
	class SearchTask extends YAsyncTask<String, Integer, Boolean>{

		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			
			ctrl.search(params[0]);
			
			return null;
		}
		protected void onPostExecute(Boolean result){
			if(!platformModel.isSearching()){
				
				Log.i("Search", "IN");
				Iterator<LyricsVO> it = platformModel.getSearchResult();
				
				data2.clear();
				
				while (it.hasNext()) {
					LyricsVO lyricsVO = (LyricsVO) it.next();
					downloadLyricsVOList.add(lyricsVO);
					
					Map<String,Object> item = new HashMap<String,Object>();
			        item.put("lyricsName", lyricsVO.getName());  
			        item.put("noteNum", lyricsVO.getNoteNum()+"");  
			        item.put("star", lyricsVO.getScore()); 
			        
			        Log.i("Search", lyricsVO.getSource()+"");
			        
			        if(lyricsVO.getSource() == Lyrics.OFFICIAL)
			        	item.put("official", true);        	
			        else 
			        	item.put("official", false);
			        
			        data2.add(item);
				}
				
				if(data2.size() == 0){
					Map<String,Object> item = new HashMap<String,Object>();
			        item.put("lyricsName", "无搜索结果T_T");   
			        item.put("star", 0); 
			        item.put("official", false);
			        
			        data2.add(item);
				}
				
				adapter.setData2(data2);
				adapter.notifyDataSetChanged();
			}
			Log.i("Search", "OUT");
			
		}
	}
	
	class DownloadTask extends YAsyncTask<Object, Integer, Long>{
		
		private int index;
		
		protected Long doInBackground(Object... params) {
			// TODO Auto-generated method stub
			
			Long id = ctrl.download((Long)params[0]);
			
			index = (Integer)params[1];
			
			return id;
		}
		
		protected void onPostExecute(Long result){
			
			downloadLyricsVOList.get(index).setId(result);
			jumpToPlay(downloadLyricsVOList.get(index));
		}
	}
}
